import groovy.json.JsonSlurper

pipeline {
    agent any
    parameters {
        booleanParam(name: 'UPDATE_PARAMS_ONLY', defaultValue: false, description: '是否只更新参数文件的配置')
        choice(name: 'DEVICE_NAME', choices: ["NQ16-0", "NQ16-1", "NQ16-2", "NQ10-3", "NQ16-AUT", "NQ10-0", "NQ10-1", "NQ10-2", "NQ10-3"], description: '请选择测试设备型号')
        string(name: 'TESTSUITE_NAME', defaultValue: '', description: '测试套件名称')
    }
    environment {
        JAVA_TOOL_OPTIONS = "-Dfile.encoding=UTF-8"
        BUILD_NUMBER = "${env.BUILD_NUMBER}"
        PARAMS_FILE = 'params.json'
        JOB_NAME = "${env.JOB_NAME}"
        LOG_DATE = new Date().format("yyyy_MM_dd")
        LOG_FILE_NAME = "${JOB_NAME}_${BUILD_NUMBER}_${params.DEVICE_NAME}_log.txt"
        REMOTE_LOG_FILE_NAME = "${params.DEVICE_NAME}_${BUILD_NUMBER}_log.txt"
        LOG_FILE_PATH = "\\\\192.168.253.179\\firmware_Submit_Test\\log\\自动化日志\\${LOG_DATE}\\${REMOTE_LOG_FILE_NAME}"
        ARCHIVE_FILE_NAME = "${JOB_NAME}_${BUILD_NUMBER}_${params.DEVICE_NAME}_log.bin"
        CHANNELS = "${params.DEVICE_NAME.split('-')[0]}"
    }
    stages {
        stage('Set Build Name and Description') {
            steps {
                script {
                    currentBuild.displayName = "#${env.BUILD_NUMBER} - ${params.DEVICE_NAME}"
                    def description = """
                        设备型号: ${params.DEVICE_NAME}
                        测试版本: ${params.VERSION}
                        测试套件: ${env.TESTSUITE_NAME}
                        模块: ${params.MODULES ?: 'all'}
                        描述: ${params.DESCRIPTION}
                    """
                    currentBuild.description = description
                }
            }
        }
        stage('Set NOTE based on DEVICE_NAME') {
            steps {
                script {
                    def deviceToNote = [
                        "NQ10-1": "KAOJI1", "NQ16-1": "KAOJI1", "NQ16-2": "KAOJI1",
                        "NQ16-3": "KAOJI2", "NQ10-2": "KAOJI2", "NQ10-3": "KAOJI2",
                        "NQ16-AUT": "auto_test",
                        "NQ16-0": "chenjinxuan"
                    ]
                    NOTE = deviceToNote[params.DEVICE_NAME] ?: "KAOJI1" // 默认为KAOJI1如果未找到匹配
                    echo "选择的DEVICE_NAME: ${params.DEVICE_NAME}"
                    echo "分配的NOTE: ${NOTE}"
                }
            }
        }
        stage('在正确的节点上运行') {
            agent { label "${NOTE}" }
            stages {
                stage('Save Build message') {
                    steps {
                        script {
                            env.BUILD_NUMBER = currentBuild.number.toString()
                        }
                    }
                }
                stage('Clone Repository') {
                    steps {
                        git url: '//192.168.253.179/firmware_src/vpAUT/nvr', branch: 'master'
                    }
                }
                stage('Load Parameters') {
                    steps {
                        script {
                            // 读取配置文件内容
                            def paramsContent = readFile(PARAMS_FILE)
                            // 解析JSON内容
                            def params = new JsonSlurper().parseText(paramsContent)
                            // 将解析后的参数存储在环境变量中
                            env.VERSIONS = params.versions.join('\n')
                            env.TESTSUITE_NAMES = params.sheet_names.join(',')
                            env.MODULES = params.modules.join(',')
                            env.TRANSLATIONS = params.translations.collect { k, v -> "$k:$v" }.join(',')
                            env.DEVICE_NAME = params.device_name.join('\n')
                        }
                    }
                }
                stage('Select Parameters') {
                    steps {
                        script {
                            properties([
                                parameters([
                                    booleanParam(name: 'UPDATE_PARAMS_ONLY', defaultValue: false, description: '是否只更新参数文件的配置'),
                                    choice(name: 'DEVICE_NAME', choices: env.DEVICE_NAME, description: '请选择测试设备型号'),
                                    choice(name: 'VERSION', choices: env.VERSIONS, description: '请选择你要执行测试的用例版本'),
                                    string(name: 'TESTSUITE_NAME', defaultValue: '', description: '测试套件名称'),
                                    booleanParam(name: 'IS_TRAVERSE_MODULES', defaultValue: false, description: '是否遍历模块执行，只有在常规用例集中有效'),
                                    extendedChoice(name: 'MODULES', type: 'PT_CHECKBOX', multiSelectDelimiter: ',', value: env.MODULES, description: '选择你要执行的模块，全部执行则选择all，只对常规和非常规用例集有效'),
                                    choice(name: 'IS_TRAVERSE_RESOLUTION', choices: ['false', 'true'], description: '是否遍历分辨率执行,需要则选择true'),
                                    string(name: 'REPEAT_TIMES', defaultValue: '1', description: '用例执行的次数'),
                                    string(name: 'DESCRIPTION', defaultValue: '常规自动化测试', description: '描述本次自动化执行目标，需要指定哪块用例')
                                ])
                            ])
                        }
                    }
                }
                stage('Install Dependencies') {
                    when {
                        expression { return !params.UPDATE_PARAMS_ONLY }
                    }
                    steps {
                        bat 'pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple'
                    }
                }
                stage('Update basic steps') {
                    when {
                        expression { return !params.UPDATE_PARAMS_ONLY }
                    }
                    steps {
                        // 先更新基础步骤
                        bat "python auto_driver/update_basic_steps.py ${params.VERSION} ${env.CHANNELS}"
                    }
                }
                stage('Translate Parameters') {
                    when {
                        expression { return !params.UPDATE_PARAMS_ONLY }
                    }
                    steps {
                        script {
                            // 解析存储在环境变量中的translations字符串
                            def translations = env.TRANSLATIONS.split(',').collectEntries { entry ->
                                def (key, value) = entry.split(':')
                                [(key): value]
                            }
                            
                            def translatedTestsuiteNames = params.TESTSUITE_NAME.split(',').collect { translations[it.trim()] ?: it.trim() }.join(',')

                            echo "Testsuite Names: ${translatedTestsuiteNames}"
                            env.TESTSUITE_NAME = translatedTestsuiteNames
                        }
                    }
                }
                stage('Generate shell script') {
                    when {
                        expression { return !params.UPDATE_PARAMS_ONLY }
                    }
                    steps {
                        script {
                            def version = params.VERSION
                            // 从 TESTSUITE_NAME 中提取 ID
                            def testsuiteNames = env.TESTSUITE_NAME.split(',')
                            def testsuiteIds = testsuiteNames.collect { name ->
                                def matcher = name =~ /.*_(\d+)$/
                                if (matcher.matches()) {
                                    return matcher[0][1]
                                }
                                return ''
                            }.findAll { it != '' }.join(',')
                            
                            echo "运行版本: ${version}"
                            echo "选择的测试套件: ${env.TESTSUITE_NAME}"
                            echo "测试套件ID: ${testsuiteIds}"
                            
                            // 为每个测试套件ID生成脚本
                            testsuiteIds.split(',').each { suiteId ->
                                // 使用新的��数格式调用脚本
                                bat "python auto_driver/generate_shell_from_excel.py ${suiteId} ${env.CHANNELS}"
                            }
                        }
                    }
                }
                stage('Run script') {
                    when {
                        expression { return !params.UPDATE_PARAMS_ONLY }
                    }
                    steps {
                        script {
                            // 从完整的测试套件名称中提取纯名称部分
                            def suiteNames = env.TESTSUITE_NAME.split(',').collect { name ->
                                def parts = name.split('_')
                                return parts[0..-2].join('_')  // 返回除最后一部分(ID)外的所有部分
                            }.join(',')
                            
                            // 使用提取出的纯名称运行脚本
                            bat "python main.py ${params.DEVICE_NAME} ${suiteNames} ${params.IS_TRAVERSE_RESOLUTION} ${env.JOB_NAME} ${env.BUILD_NUMBER} ${params.REPEAT_TIMES} ${params.DESCRIPTION}"
                        }
                    }
                }
            }
            post {
                always {
                    script {
                        if (!params.UPDATE_PARAMS_ONLY && currentBuild.result != 'ABORTED') {
                            
                            try {
                                def finalLogDate = new Date().format("yyyy_MM_dd")
                                def finalLogFilePath = "\\\\192.168.253.179\\firmware_Submit_Test\\log\\自动化日志\\${finalLogDate}\\${LOG_FILE_NAME}"
        
                                bat "if not exist \"${WORKSPACE}\\archived_logs\" mkdir \"${WORKSPACE}\\archived_logs\""
                                bat "copy \"${finalLogFilePath}\" \"${WORKSPACE}\\archived_logs\\${ARCHIVE_FILE_NAME}\""
                                
                                def artifactPath = archiveArtifacts(artifacts: "archived_logs\\${ARCHIVE_FILE_NAME}", allowEmptyArchive: true)
                                def buildUrl = env.BUILD_URL
                                def downloadUrl = "${buildUrl}artifact/archived_logs/${ARCHIVE_FILE_NAME}"
                                
                                writeFile file: "${WORKSPACE}\\download_link.txt", text: downloadUrl
                                bat "del \"${WORKSPACE}\\archived_logs\\${ARCHIVE_FILE_NAME}\""
                                
                                echo "Log file download link: ${downloadUrl}"
                            } catch (Exception e) {
                                echo "日志文件归档失败: ${e.message}"
                            }
                            
                            allure([
                                includeProperties: false,
                                jdk: '',
                                properties: [],
                                reportBuildPolicy: 'ALWAYS',
                                results: [[path: 'allure-results']]
                            ])
                            
                        } else if (params.UPDATE_PARAMS_ONLY) {
                            echo "仅更新配置，不触发下次测试"
                        } else {
                            echo "手动停止任务，不再自动执行."
                        }
                        echo '流水线结束'
                    }
                }
            }
        }
    }
   

}
